package lv.dysnomia.portal.web

import com.google.appengine.api.blobstore.BlobInfo
import com.google.appengine.api.blobstore.BlobInfoFactory
import java.io.IOException;
import java.util.{ Map => JavaMap, Date }

import javax.servlet.ServletException;
import javax.servlet.http.{ HttpServlet, HttpServletRequest, HttpServletResponse }
import com.google.appengine.api.blobstore.{ BlobKey, BlobstoreServiceFactory }
import com.google.appengine.api.users.{ User, UserService, UserServiceFactory }
import lv.dysnomia.server.entities.MediaFile

class UploadBlob extends HttpServlet {
  val blobstoreService = BlobstoreServiceFactory.getBlobstoreService
  val blobInfoFactory = new BlobInfoFactory
  override def doPost(request: HttpServletRequest, response: HttpServletResponse): Unit = {
    val userService = UserServiceFactory.getUserService
    val user = userService.getCurrentUser
    val fileName = "unknown"
    val blobs: JavaMap[String, BlobKey] = blobstoreService.getUploadedBlobs(request)
    val blobKey: BlobKey = blobs.get("myFile")
    if (blobKey == null) {
      response.sendRedirect("/simple/index.html")
    } else {
      val blobInfo: BlobInfo = blobInfoFactory.loadBlobInfo(blobKey)
      val mediaFile = new MediaFile(user, new Date, blobInfo.getFilename, blobKey.getKeyString())
      mediaFile.setFileName(blobInfo.getFilename)
      val pm = PMF.getInstance.getPersistenceManager
      try {
        pm.makePersistent(mediaFile)
      } finally {
        pm.close()
      }
      response.sendRedirect("/servlet/serve-blob?blob-key=" + blobKey.getKeyString() + "&size=" + blobs.size)
    }
  }
}
